/*
 * Copyright (C) 2012 CyberAgent
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.wu.family.publish.photo;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.wu.family.MainGroupActivity;
import com.wu.family.R;
import com.wu.family.publish.photo.utils.CameraHelper;
import com.wu.family.publish.photo.utils.CameraHelper.CameraInfo2;
import com.wu.family.publish.photo.utils.GPUImageFilterTools;
import com.wu.family.publish.photo.utils.GPUImageFilterTools.FilterAdjuster;
import com.wu.family.publish.photo.utils.GPUImageFilterTools.OnGpuImageFilterChosenListener;
import com.wu.family.views.GridLineView;

import jp.co.cyberagent.android.gpuimage.GPUImage;
import jp.co.cyberagent.android.gpuimage.GPUImage.OnPictureSavedListener;
import jp.co.cyberagent.android.gpuimage.GPUImageFilter;
import android.R.integer;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.Size;
import android.net.Uri;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;

public class CameraFilterActivity extends Activity implements OnSeekBarChangeListener,
        OnClickListener {

    private GPUImage mGPUImage;
    private CameraHelper mCameraHelper;
    private CameraLoader mCamera;
    private GPUImageFilter mFilter;
    private FilterAdjuster mFilterAdjuster;

    private GLSurfaceView glSurfaceView;
    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.camera_filter);
        ((SeekBar) findViewById(R.id.seekBar)).setOnSeekBarChangeListener(this);
        findViewById(R.id.btnClose).setOnClickListener(this);
        findViewById(R.id.btnCamera).setOnClickListener(this);
        findViewById(R.id.btnGridline).setOnClickListener(this);
        findViewById(R.id.btnSwitch).setOnClickListener(this);
        findViewById(R.id.btnFlashing).setOnClickListener(this);
        findViewById(R.id.btnFilter).setOnClickListener(this);

        glSurfaceView = (GLSurfaceView) findViewById(R.id.surfaceView);
        ViewGroup.LayoutParams lp = glSurfaceView.getLayoutParams();
  		lp.height = getWindowManager().getDefaultDisplay().getWidth();
  		glSurfaceView.setLayoutParams(lp);
  		
        mGPUImage = new GPUImage(this);
        mGPUImage.setGLSurfaceView(glSurfaceView);

        mCameraHelper = new CameraHelper(this);
        mCamera = new CameraLoader();

        if (!mCameraHelper.hasFrontCamera() || !mCameraHelper.hasBackCamera()) {
        	findViewById(R.id.btnSwitch).setVisibility(View.GONE);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mCamera.onResume();
    }

    @Override
    protected void onPause() {
        mCamera.onPause();
        super.onPause();
    }

    @Override
    public void onClick(final View v) {
        switch (v.getId()) {
        	case R.id.btnClose:
            	finish();
            break;
            
            case R.id.btnFilter:
                GPUImageFilterTools.showDialog(this, new OnGpuImageFilterChosenListener() {

                    @Override
                    public void onGpuImageFilterChosenListener(final GPUImageFilter filter) {
                        switchFilterTo(filter);
                    }
                });
                break;

            case R.id.btnCamera:
                /*if (mCamera.mCameraInstance.getParameters().getFocusMode().equals(
                        Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) {//PICTURE
                    takePicture();
                } else */{
                    mCamera.mCameraInstance.autoFocus(new Camera.AutoFocusCallback() {

                        @Override
                        public void onAutoFocus(final boolean success, final Camera camera) {
                            takePicture();
                        }
                    });
                }
                break;
                
            case R.id.btnGridline:
            	GridLineView glView = (GridLineView) findViewById( R.id.glView );
            	glView.setVisibility(glView.isShown()?View.GONE:View.VISIBLE);
            	
                break;
            
            case R.id.btnSwitch:
                mCamera.switchCamera();
                break;
                
            case R.id.btnFlashing:
            	ImageButton ibBtnFlashing = (ImageButton) findViewById( R.id.btnFlashing );
            	Integer tag = (Integer)ibBtnFlashing.getTag();
    			tag = (tag == null)?0:tag;
    			tag = tag%3;
    			if (tag == 0) {
    				mCamera.setFlashMode(Camera.Parameters.FLASH_MODE_ON);
    				ibBtnFlashing.setImageResource(R.drawable.flashing_on);
    			}else if (tag == 1) {
    				mCamera.setFlashMode(Camera.Parameters.FLASH_MODE_AUTO);
    				ibBtnFlashing.setImageResource(R.drawable.flashing_auto);
    			}else {
    				mCamera.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
    				ibBtnFlashing.setImageResource(R.drawable.flashing_off);
    			}
    			ibBtnFlashing.setTag(++tag);
    			
                break;
            
        }
    }

    private void takePicture() {
        // TODO get a size that is about the size of the screen
        /*Camera.Parameters params = mCamera.mCameraInstance.getParameters();
        params.setPictureSize(1280, 960);
        params.setRotation(90);
        mCamera.mCameraInstance.setParameters(params);*/
        /*for (Camera.Size size2 : mCamera.mCameraInstance.getParameters()
                .getSupportedPictureSizes()) {
            Log.i("ASDF", "Supported: " + size2.width + "x" + size2.height);
        }*/
        mCamera.mCameraInstance.takePicture(null, null,
                new Camera.PictureCallback() {

                    @Override
                    public void onPictureTaken(byte[] data, final Camera camera) {

                        final File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
                        if (pictureFile == null) {
                            Log.d("ASDF",
                                    "Error creating media file, check storage permissions");
                            return;
                        }

                        try {
                            FileOutputStream fos = new FileOutputStream(pictureFile);
                            fos.write(data);
                            fos.close();
                            fos = null;
                        } catch (FileNotFoundException e) {
                            Log.d("ASDF", "File not found: " + e.getMessage());
                        } catch (IOException e) {
                            Log.d("ASDF", "Error accessing file: " + e.getMessage());
                        }

                        data = null;
                       /* Bitmap bitmap = BitmapFactory.decodeFile(pictureFile
                                .getAbsolutePath());*/
                        // mGPUImage.setImage(bitmap);
                        final GLSurfaceView view = (GLSurfaceView) findViewById(R.id.surfaceView);
                        view.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
                        /*mGPUImage.saveToPictures(bitmap, "FamilyCameraFilter",
                        		new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + ".jpg",
                                new OnPictureSavedListener() {

                                    @Override
                                    public void onPictureSaved(final Uri
                                            uri) {
                                        //pictureFile.delete();
                                        camera.startPreview();
                                        view.setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY);
                                        
                                        Intent intent = new Intent(CameraFilterActivity.this, PhotoEditorActivity.class);
                        				intent.setData(uri);
                        				startActivity(intent);
                        				finish();
                                    }
                                });*/
                        /*MediaScannerConnection.scanFile(mContext,
                                new String[] {
                                    file.toString()
                                }, null,
                                new MediaScannerConnection.OnScanCompletedListener() {
                                    @Override
                                    public void onScanCompleted(final String path, final Uri uri) {
                                        if (mListener != null) {
                                            mHandler.post(new Runnable() {

                                                @Override
                                                public void run() {
                                                    mListener.onPictureSaved(uri);
                                                }
                                            });
                                        }
                                    }
                                });*/
                        Intent intent = new Intent(CameraFilterActivity.this, PhotoEditorActivity.class);
        				//intent.setData(Uri.fromFile(pictureFile));
        				intent.putExtra("path", pictureFile.getAbsolutePath());
        				startActivity(intent);
        				finish();
                    }
                });
    }

    public static final int MEDIA_TYPE_IMAGE = 1;
    public static final int MEDIA_TYPE_VIDEO = 2;

    private static File getOutputMediaFile(final int type) {
        // To be safe, you should check that the SDCard is mounted
        // using Environment.getExternalStorageState() before doing this.

        File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES), "FamilyCamera");
        // This location works best if you want the created images to be shared
        // between applications and persist after your app has been uninstalled.

        // Create the storage directory if it does not exist
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                Log.d("MyCameraApp", "failed to create directory");
                return null;
            }
        }

        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File mediaFile;
        if (type == MEDIA_TYPE_IMAGE) {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator +
                    "IMG_" + timeStamp + ".jpg");
        } else if (type == MEDIA_TYPE_VIDEO) {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator +
                    "VID_" + timeStamp + ".mp4");
        } else {
            return null;
        }

        return mediaFile;
    }

    private void switchFilterTo(final GPUImageFilter filter) {
        if (mFilter == null
                || (filter != null && !mFilter.getClass().equals(filter.getClass()))) {
            mFilter = filter;
            mGPUImage.setFilter(mFilter);
            mFilterAdjuster = new FilterAdjuster(mFilter);
        }
    }

    @Override
    public void onProgressChanged(final SeekBar seekBar, final int progress, final boolean fromUser) {
        if (mFilterAdjuster != null) {
            mFilterAdjuster.adjust(progress);
        }
    }

    @Override
    public void onStartTrackingTouch(final SeekBar seekBar) {
    }

    @Override
    public void onStopTrackingTouch(final SeekBar seekBar) {
    }

    private class CameraLoader {
        private int mCurrentCameraId = 0;
        private Camera mCameraInstance;

        public void onResume() {
            setUpCamera(mCurrentCameraId);
        }

        public void onPause() {
            releaseCamera();
        }

        public void switchCamera() {
            releaseCamera();
            mCurrentCameraId = (mCurrentCameraId + 1) % mCameraHelper.getNumberOfCameras();
            setUpCamera(mCurrentCameraId);
        }

        public void setFlashMode(String mode) {
        	Parameters parameters = mCameraInstance.getParameters();
        	parameters.setFlashMode(mode);
            mCameraInstance.setParameters(parameters);
            mCameraInstance.startPreview();
        }
        
        private void setUpCamera(final int id) {
            mCameraInstance = getCameraInstance(id);
            Parameters parameters = mCameraInstance.getParameters();
            // TODO adjust by getting supportedPreviewSizes and then choosing
            // the best one for screen size (best fill screen)
            List<Size> mSupportedPreviewSizes = parameters.getSupportedPreviewSizes();
            List<Size> mSupportedPictureSizes = parameters.getSupportedPictureSizes();
            Size mPreviewSize = null;
            Size mPictureSize = null;
            
            int width = getWindowManager().getDefaultDisplay().getWidth();
            int height = getWindowManager().getDefaultDisplay().getHeight();
            if (mSupportedPreviewSizes != null) {
   	            mPreviewSize = getOptimalPreviewSize(mSupportedPreviewSizes, width, width);
   	        }
            if (mSupportedPictureSizes != null) {
            	mPictureSize = getOptimalPreviewSize(mSupportedPictureSizes, width, width);
   	        }
            
            parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
            parameters.setPictureSize(mPictureSize.width, mPictureSize.height);
            if (parameters.getSupportedFocusModes().contains(
                    Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) {//PICTURE "continuous-picture"
                parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
            }
            parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);

            int orientation = mCameraHelper.getCameraDisplayOrientation(
                    CameraFilterActivity.this, mCurrentCameraId);
            CameraInfo2 cameraInfo = new CameraInfo2();
            mCameraHelper.getCameraInfo(mCurrentCameraId, cameraInfo);
            boolean flipHorizontal = cameraInfo.facing == CameraInfo.CAMERA_FACING_FRONT
                    ? true : false;
            
            parameters.setRotation(flipHorizontal?270:90);
            mCameraInstance.setParameters(parameters);
            
            mGPUImage.setUpCamera(mCameraInstance, orientation, flipHorizontal, false);
        }

        private Size getOptimalPreviewSize(List<Size> sizes, int w, int h) {
            final double ASPECT_TOLERANCE = 0.02;
            final double LOW_ASPECT_TOLERANCE = 0.30;
            
            if (sizes == null) return null;

            Size optimalSize = null;
            double minDiff = Double.MAX_VALUE;
            
            //because Size.width > Size.height
            final int targetHeight = h>w?w:h;
            final int targetwidth = h>w?h:w;
            double targetRatio = (double)targetwidth/targetHeight;

            // Try to find an size match aspect ratio and size
            for (double aspect = ASPECT_TOLERANCE; 
            		aspect < LOW_ASPECT_TOLERANCE && optimalSize == null; aspect=aspect+0.01) {
            	for (Size size : sizes) {
    	            double ratio = (double) size.width / size.height;
    	            if (Math.abs(ratio - targetRatio) > aspect) continue;
    	            if (Math.abs(size.height - targetHeight) < minDiff) {
    	                optimalSize = size;
    	                minDiff = Math.abs(size.height - targetHeight);
    	            }
    	        }
    		}
            //System.out.println(targetwidth+":"+targetHeight);
            // Cannot find the one match the aspect ratio, ignore the requirement
            if (optimalSize == null) {
                minDiff = Double.MAX_VALUE;
                for (Size size : sizes) {
                	double curDiff = Math.pow(size.height - targetHeight, 2) 
                			+ Math.pow(size.width - targetwidth, 2)
                			/*Math.abs(size.height - targetHeight)*/;
                	//System.out.println("Size"+size.width + ":"+size.height);
                    if (curDiff < minDiff) {
                        optimalSize = size;
                        minDiff = curDiff;
                    }
                }
                //System.out.println("optimalSize null"+optimalSize.width + ":"+optimalSize.height);
            }else {
            	//System.out.println("optimalSize"+optimalSize.width + ":"+optimalSize.height);
    		}
            System.out.println("optimalSize"+optimalSize.width + ":"+optimalSize.height);
            
            return optimalSize;
        }
        
        /** A safe way to get an instance of the Camera object. */
        private Camera getCameraInstance(final int id) {
            Camera c = null;
            try {
                c = mCameraHelper.openCamera(id);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return c;
        }

        private void releaseCamera() {
            mCameraInstance.setPreviewCallback(null);
            mCameraInstance.release();
            mCameraInstance = null;
        }
    }
}
